package com.bang.springcloud.report.service.impl;

import com.bang.framework.common.FastJsonConvertUtil;
import com.bang.framework.mq.constants.QueueConstants;
import com.bang.springcloud.report.entity.BrokerMessageLog;
import com.bang.springcloud.report.entity.Order;
import com.bang.springcloud.report.mapper.BrokerMessageLogMapper;
import com.bang.springcloud.report.mapper.OrderMapper;
import com.bang.springcloud.report.service.IOrderService;
import com.bang.springcloud.report.util.OrderSendUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author bang
 * @since 2019-12-10
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private BrokerMessageLogMapper brokerMessageLogMapper;

    @Autowired
    private OrderSendUtils orderSendUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order) throws Exception {
        // order current time
        LocalDateTime now = LocalDateTime.now();
        order.setAddtime(now).setFlag(1).setUserId(1L).setOrderType(1).setMoney(BigDecimal.ONE);
        // order insert
        this.saveOrUpdate(order);
        // log insert
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        brokerMessageLog.setMessageId(order.getOrderNo());
        //save order message as json
        brokerMessageLog.setMessage(FastJsonConvertUtil.convertObjectToJSON(order));
        brokerMessageLog.setStatus("0");
        brokerMessageLog.setNextRetry(now.minusMinutes(1));
        brokerMessageLog.setCreateTime(now);
        brokerMessageLog.setUpdateTime(now);
        brokerMessageLogMapper.insert(brokerMessageLog);
        // order message sender
        orderSendUtils.send(order, new CorrelationData(order.getOrderNo()), QueueConstants.Queue.BANG_TEST_DEFAULT_QUEUE);
    }
}
